package com.dk.mq;

import com.dk.util.JavaMailUtil;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "auction",consumerGroup = "myconsumer-group")
public class MqConsumer implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void onMessage(String s) {

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt messageExt = list.get(0);
                Boolean b = redisTemplate.boundHashOps("messageID").hasKey(messageExt.getMsgId());
                if (!b){
                    int reconsumeTimes = messageExt.getReconsumeTimes();
                    try {
                        String message = new String(messageExt.getBody(),"utf-8");
                        System.out.println("mq接受到消息"+message);
                        String[] msgs = message.split(",");
                       javaMailUtil.test("拍卖申请通知",msgs[1],msgs[0]);

                        redisTemplate.boundHashOps("messageID").put(messageExt.getMsgId(),"ok");
                    }catch (Exception e){
                        System.out.println("重试次数："+reconsumeTimes);
                        if (reconsumeTimes>2){
                            System.out.println("已重试3次，进入自定义死信表中");
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        }
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
